/**
 * Created by joustany on 17/12/13.
 */
ajaxStart()
ajaxComplete()
var params = JSON.parse(window.localStorage.user);
var redirect = JSON.parse(decodeURIComponent(params['redirect']));
ap.showOptionButton();

// console.log(redirect)
// console.log(params)
// console.log(configApi('/deposit/details'),)
$.ajax({
    url: configApi('/deposit/details'),
    data: {
        access_token: redirect.token
    },
    dataType: 'json',
    type: "get",
    success:function (res) {
        if (res.success){
            topUpDetails(res.data)
        }else {
            layer.open({
                content: res.message
                ,skin: 'msg'
                ,time: 2 //2秒后自动关闭
            });
        }
    },
    error:function () {
        layer.open({
            content: "服务器异常,请退出重试"
            ,skin: 'msg'
            ,time: 2 //2秒后自动关闭
        });
    }
})
var data = {
    "details": [
        {
            "limit": "50",
            "coupon": "10"
        },
        {
            "limit": "100",
            "coupon": "20"
        },
        {
            "limit": "150",
            "coupon": "40"
        },
        {
            "limit": "200",
            "coupon": "60"
        }
    ],
    "text": "充值50元赠送10元券（2张5元券）、100元赠送20元券（4张5元券）、150元赠送40元券（8张5元券）、200元赠送60元券（12张5元券），以上赠送的红包抵用券均为发放后30天，满10元可用，单笔消费仅限1张。"
}
function topUpDetails(data) {
    console.log(data)
    var details = data.details
    var html = ''
    $.each(details,function (index,item) {
        console.log(item)
        if (item.limit === 1000){
            html +='<div class="topUp-content shade" onclick="topUpHandle(this,'+item.limit+')">'
            html +='<div class="money"><span class="num">'+ item.limit +'</span>元</div>'
            html +='<div class="send-money">赠送取暖器一台</div>'
            html +='</div>'
        }else {
            html +='<div class="topUp-content" onclick="topUpHandle(this,'+item.limit+')">'
            html +='<div class="money"><span class="num">'+ item.limit +'</span>元</div>'
            html +='<div class="send-money">送'+ item.coupon +'元红包</div>'
            html +='</div>'
        }
    })
    $('.toUp-container').prepend(html)
    $('.topUp-state').append('<p class="text">3.'+ data.text[0]+'</p>')
    $('.topUp-state').append('<p class="text">4.'+ data.text[1]+'</p>')
}
function agreeHandle() {
    window.location.href = './agreement.html'
}
var clickFlag = false
var jsApiParameters //支付签名参数
var orderInfo //订单号
function topUpHandle(that,limit) {
    // console.log(clickFlag)
    // console.log(params.platform)
    if(params.platform =='wechat' && clickFlag){
        return
    }
    console.log('s')
    clickFlag = true
    // $('.loding').show()
    _hmt.push(["_trackEvent", "充值", "选择金额","",limit]);
    $(that).siblings().removeClass('pitchOn')
    $(that).addClass('pitchOn')
    $.ajax({
        url: configApi('/deposit/deposit'),
        data: {
            access_token: redirect.token,
            money: limit,
            platform: params.platform,
            device_id:redirect.id
        },
        dataType: 'json',
        type: "post",
        aysnc:false,
        success: function (res) {
            if (res.success) {
                console.log(res)
                jsApiParameters = res.data.wxPayParams
                orderInfo = res.data.order.order_no
                if (params.platform === 'wechat'){
                    callpay()
                }else {
                    // console.log(res.data.aliPayUrl)
                    window.location.href = res.data.aliPayUrl;
                }
                // $('.loding').hide()
            } else {
                clickFlag = false
                layer.open({
                    content: res.message
                    , skin: 'msg'
                    , time: 2 //2秒后自动关闭
                });
            }
        },
        error: function () {
            layer.open({
                content: "服务器异常,请退出重试"
                , skin: 'msg'
                , time: 2 //2秒后自动关闭
            });
        }
    })
}
function jsApiCall() {
    console.log(jsApiParameters)
    WeixinJSBridge.invoke(
        'getBrandWCPayRequest', {
            "appId": jsApiParameters.appId,     //公众号名称，由商户传入
            "timeStamp": jsApiParameters.timeStamp,         //时间戳，自1970年以来的秒数
            "nonceStr": jsApiParameters.nonceStr, //随机串
            "package": jsApiParameters.package,
            "signType": jsApiParameters.signType,         //微信签名方式：
            "paySign": jsApiParameters.paySign //微信签名
        },
        function (res) {
            // 支付测试环境还要将测试人员的微信号在公众号平台中加入测试支付白名单,不然调不起支付密码框
            // 返回信息get_brand_wcpay_request:ok
            //alert(res.errMsg)
            // alert(clickFlag)
            clickFlag = false
            if (res.err_msg == "get_brand_wcpay_request:ok") {
                window.location.href = './topUpResult.html?order_no='+ orderInfo+'';
            } else {
                // _payFlag = true;
                // zhuge.track('取消支付', {
                //     '支付方式': 'wechat',
                //     '订单编号': orderInfo.order_no
                // }, function () {
                //     // window.location.href = './views/payResult.html' + '?result=1';
                // });
            }
        }
    )
}
function callpay() {
    if (typeof WeixinJSBridge == "undefined") {
        if (document.addEventListener) {
            document.addEventListener('WeixinJSBridgeReady', jsApiCall, false);
        } else if (document.attachEvent) {
            document.attachEvent('WeixinJSBridgeReady', jsApiCall);
            document.attachEvent('onWeixinJSBridgeReady', jsApiCall);
        }
    } else {
        jsApiCall();
    }
}
